from django.http import HttpResponse
from django.http import HttpRequest
from mbserver.source.models import Source
from mbserver.server.lib import utils
from mbserver.server.core.pool import MBThreadPool
from mbserver.cache import cache
import simplejson

import logging
log = logging.getLogger('metabus')

def process(request):
    pool = MBThreadPool()

    if request.POST:
        sources = simplejson.loads(request.POST['sources'])
        keywords = utils.get_formated_keywords(request.POST['keyword'])
        log.debug("Posted: key '%s' in '%s'" % (keywords, request.POST['sources']))

        for source_id in sources:
            search = dict() 

            try:
                source = Source.objects.get(id=int(source_id))
            except:
                log.error('unknown source id %s' % source_id)
                continue

            search['source'] = source
            search['keyword'] = utils.safe_unicode(keywords)

            # Put the request in queue to be processed by the threads
            if cache.get(search) is None:
                # High priority
                log.debug('adding high priority search: %s' % search)
                pool.requests.put(search)
            else:
                # Low priority
                log.debug('adding low priority search: %s' % search)
                pool.bg_requests.put(search)
    else:
        log.error("No post array")
    
    return HttpResponse(simplejson.dumps({'return': 'success'}))
